<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/* Author: Jorge Torres
 * Description: Login model class
 */
class Authentication_model extends CI_Model{
	function __construct(){
		parent::__construct();
		$this->load->helper('security');
	}
	
	public function validate(){
		// grab user input
		$username = $this->security->xss_clean($this->input->post('username'));
		$password = $this->security->xss_clean($this->input->post('password'));
		$password = $str = do_hash($password, 'md5');
		// Prep the query
		$this->db->where('username', $username);
		$this->db->where('password', $password);
		
		// Run the query
		$query = $this->db->get('usuario');
		// Let's check if there are any results
		if($query->num_rows == 1)
		{
			// If there is a user, then create session data
			$row = $query->row();
			$data = array(
					'id_usuario'  => $row->id,
					'nombre'  => $row->nombre. ' '.$row->apellido,
					'username'  => $row->username,
					'correo'     => $row->correo,
					'validated' => true
					);
			$this->session->set_userdata($data);
			return true;
		}
		// If the previous process did not validate
		// then return false.
		return false;
	}
	
	/**
	 * Validates existing users by usernames to avoid repeated
	 * @return boolean return true if exists in database the username
	 */
	public function existing_user(){
		// grab user input
		$username = $this->security->xss_clean( $this->input->post('username') );
		// Prep the query
		$this->db->where('username', $username);	
		// Run the query
		$query = $this->db->get('usuario');
		// Let's check if there are any results
		if( $query->num_rows >= 1 )
		{
			// If there is a user, then return true to avoid repeated usernames		
			return true;
		}		
		return false;
	}
	
	public function save_user(){
		$this->load->library('rb');
		$usuario  = R::dispense("usuario");
		$usuario->nombre = $this->input->post('nombre');
		$usuario->apellido = $this->input->post('apellido');
		$usuario->username =  $this->input->post('username');
		$usuario->password =  $this->input->post('password');
		$usuario->correo =  $this->input->post('correo');
		$usuario->created_on	=  date('Y-m-d H:i:s', time());
		$id_usuario= R::store($usuario);
		if ( $id_usuario > 0 ){
			$newdata = array(
					'id_usuario'  => $id_usuario,
					'nombre'  => $usuario->nombre. ' '.$usuario->apellido,
					'username'  => $usuario->username,
					'correo'     => $usuario->correo,
					'validated' => TRUE
			);
			$this->session->set_userdata($newdata);
		}
		return ( $id_usuario > 0 );
	}
}
?>